package com.dongdong.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.dongdong.config.AlipayConfig;
import com.dongdong.data.DataResult;
import com.dongdong.data.ResponseStatusEnum;
import com.dongdong.pojo.*;
import com.dongdong.service.*;
import com.dongdong.util.IdWorker;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Deacription TODO
 * @Author Lenovo
 * @Date 2020/12/22 16:29
 * @Version 1.0
 **/
@Controller
@RequestMapping("orderController")
public class OrderController {

    private final Logger logger= LoggerFactory.getLogger(OrderController.class);

    @Reference
    private AddressService addressService;

    @Reference
    private OrderService orderService;

    @Reference
    private SellerService sellerService;

//    @Resource
//    private IdWorker idWorker;

    @Reference
    private OrderItemService orderItemService;

    @Reference
    private PayLogService payLogService;

    @Autowired
    private AlipayClient alipayClient;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    Long id=(long)0;
    String userName="";

    @Resource
    private IdWorker idWorker;

    @RequestMapping("getOrderInfo")
    public String getOrderInfo(){
        return "getOrderInfo";
    }

    @RequestMapping("insertOrder")
    @ResponseBody
    public DataResult insertOrder(TbOrder order, Long addressId){
        try {
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            id = user.getId();
            userName = user.getUsername();
            TbOrder tbOrder = addressService.getReceiver(addressId,order);
            tbOrder.setUserId(user.getUsername());
            Map<String,String> map=orderService.addOrder(tbOrder);

//          发送延迟消息
            sendMessage(map.get("payOrder"));
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(map);
        }catch (Exception e){
            logger.error("增加错误",e);
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    //            发送延迟消息
    private void sendMessage(String payOrder) {
        System.out.println("进入方法");
        //建立要发送的消息 发送的内容是byte[]数组要转换
        Message msg = new Message("orderStatus",payOrder.getBytes());
        //延时消息
        msg.setDelayTimeLevel(4);
        try {
            //MessageQueueSelector 消息对列选择器（告诉要选择那个队列）
            rocketMQTemplate.getProducer().send(msg);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("tradePay")
    @ResponseBody
    public String tradePay(String out_trade_no,String subject,String total_amount,String body){
        //获得初始化的AlipayClient
        //AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getApp_id(),
                //alipayConfig.getMerchant_private_key(), alipayConfig.getFormate(), alipayConfig.getCharset(),
                //alipayConfig.getAlipay_public_key(), alipayConfig.getSign_type());

        //创建支付交易的对象
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //设置请求参数
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出
        return result;
    }

    //异步回调
    @RequestMapping("notifyUrl")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request, String out_trade_no, String trade_no,String gmt_create,String total_amount, String trade_status,String gmt_payment,String out_biz_no) throws ParseException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            //验签 查看数字签名是否被别人篡改
            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        if(signVerified) {//验证成功
            //商户订单号
            //String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            // String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            //String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            //校验 订单id 支付金额 商家是否和付款保持一致，避免被人篡改信息
            //商户订单号
            System.out.println("商户订单号："+out_trade_no);
            //支付宝交易号
            System.out.println("支付宝交易号:"+trade_no);
            //交易状态
            System.out.println("交易状态:"+trade_status);
            System.out.println("创建时间"+gmt_create);
            System.out.println("支付时间"+gmt_payment);
            System.out.println("金额"+total_amount);
            if(out_biz_no != null || "".equals(out_biz_no)){
                //System.out.println("退款成功");
                return "success";
            }
            //更新paylog和order中状态；清除redis中母订单；调用积分模块等
            TbPayLog payLog = new TbPayLog();
            payLog.setOutTradeNo(out_trade_no);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            payLog.setCreateTime(simpleDateFormat.parse(gmt_create));
            payLog.setPayTime(simpleDateFormat.parse(gmt_payment));
            payLog.setTransactionId(trade_no);
            payLog.setTradeState("2");//已付款
            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
//                List<String> list = Arrays.asList(userName,String.valueOf(id), total_amount);
//                sendTXMessage.txMessage(list,payLog);
                System.out.println("异步交易成功");
                System.out.println(trade_no);
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }

            return "success";

        }else {//验证失败
            System.out.println("验证失败");
            return "fail";

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }

    //同步回调
    @RequestMapping("returnUrl")
    @ResponseBody
    public String returnUrl(HttpServletRequest request, String out_trade_no, String trade_no, String total_amount, Model model){
        //获取支付宝GET过来反馈信息
//        Map<String,String> params = new HashMap<String,String>();
//        Map<String,String[]> requestParams = request.getParameterMap();
//        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            //乱码解决，这段代码在出现乱码时使用
//            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//            params.put(name, valueStr);
//        }
//
//        boolean signVerified = false; //调用SDK验证签名
//        try {
//            signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(true) {
            //商户订单号
            //String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            //String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            //String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            //商户订单号
            System.out.println("商户订单号："+out_trade_no);
            //支付宝交易号
            System.out.println("支付宝交易号:"+trade_no);
            //付款金额
            System.out.println("付款金额："+total_amount);
            model.addAttribute("out_trade_no",out_trade_no);
            model.addAttribute("trade_no",trade_no);
            model.addAttribute("total_amount",total_amount);
            //编写业务
            return "paysuccess";
        }else {
            model.addAttribute("msg","验签失败");
            return "payfail";
        }
    }

    @RequestMapping("orderReceive")
    public String orderReceive(){
        return "home-order-receive";
    }

    @RequestMapping("getOrder")
    @ResponseBody
    public DataResult getOrder(){
        try {
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            List<Cart> carts = new ArrayList<>();
            List<TbOrder> orderList = orderService.getOrderByUserName(user.getUsername());
            for (TbOrder tbOrder : orderList) {
                Cart cart = new Cart();
                String sellerId = tbOrder.getSellerId();
                cart.setSellerId(sellerId);
                String sellerName = sellerService.getNameById(tbOrder.getSellerId());
                cart.setSellerName(sellerName);
                List<TbOrderItem> orderItemList = orderItemService.getByOrderId(tbOrder.getOrderId());
                for (TbOrderItem orderItem : orderItemList) {
                    orderItem.setIdStr(String.valueOf(orderItem.getId()));
                }
                cart.setOrderItemList(orderItemList);
                cart.setPayOrder(String.valueOf(tbOrder.getPayOrder()));
                carts.add(cart);

            }
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(carts);
        }catch (Exception e){
            logger.error("退款失败");
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    @RequestMapping("toRefund")
    @ResponseBody
    public DataResult toRefund(String idStr){
        try {
            TbOrderItem orderItem = orderItemService.selectById(Long.parseLong(idStr));
            TbOrder order = orderService.selectOrderByOrderId(orderItem.getOrderId());
            orderItemService.updateStatus(Long.parseLong(idStr));
            Map<String,String> map = new HashMap<>();
            map.put("out_trade_no",String.valueOf(order.getPayOrder()));
            map.put("trade_no",order.getAlipayOrder());
            map.put("refund_amount",String.valueOf(orderItem.getTotalFee()));
            map.put("refund_reason","质量问题");
            map.put("out_request_no",String.valueOf(idWorker.nextId()));
            return DataResult.response(ResponseStatusEnum.SUCCESS).setData(map);
        } catch (Exception e) {
            logger.error("操作异常", e);
            return DataResult.response(ResponseStatusEnum.INTERNAL_SERVER_ERROR);
        }
    }

    //退款交易
    @RequestMapping("tradeRefund")
    @ResponseBody
    public String tradeRefund(String out_trade_no,String trade_no,String refund_amount,String refund_reason,String out_request_no,Model model){
        //获得初始化的AlipayClient
        //AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        //String out_trade_no = new String(request.getParameter("WIDTRout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
        //支付宝交易号
        //String trade_no = new String(request.getParameter("WIDTRtrade_no").getBytes("ISO-8859-1"),"UTF-8");
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        //String refund_amount = new String(request.getParameter("WIDTRrefund_amount").getBytes("ISO-8859-1"),"UTF-8");
        //退款的原因说明
        //String refund_reason = new String(request.getParameter("WIDTRrefund_reason").getBytes("ISO-8859-1"),"UTF-8");
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        //String out_request_no = new String(request.getParameter("WIDTRout_request_no").getBytes("ISO-8859-1"),"UTF-8");

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"trade_no\":\""+ trade_no +"\","
                + "\"refund_amount\":\""+ refund_amount +"\","
                + "\"refund_reason\":\""+ refund_reason +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");

        //请求
        String result = null;
        try {
            result = alipayClient.execute(alipayRequest).getBody();
            model.addAttribute("refund_amount",refund_amount);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出
        return result;
    }


}



